﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;
using System.Windows;

namespace SUNRPA.CONTROLS.IMPL.controls {
    /// <summary>
    /// TODO: 此控件有待完善功能有
    /// 1、模拟人工输入时按键时间间隔
    /// 2、剪切板输入功能
    /// 3、等待元素出现超时功能
    /// 4、输入前点击元素功能
    /// 
    /// 此控件现在默认是的输入方式是：调用元素自身的自动化接口输入功能（直接对元素内容属性进行赋值操作）
    /// </summary>
    public class TypeWebInputNAction : BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            TypeWebInputNParam? param = item.ControlParam as TypeWebInputNParam;
            WebElement ele = param.WebEle as WebElement;
            //判断是否为web元素
            if(ele == null){ 
                throw new RpaRuntimeException("元素不是web元素，无法进行web输入操作");
            }
            string webObject = param.WebObj;
            WebPage webPage = this.GetObjVar<WebPage>(ref webObject, globleData);
            if(webPage == null){ 
                throw new RpaRuntimeException("网页为空，无法进行web输入操作");
            }
            int inputType = param.InputType;
            //是否追加
            bool append = param.Append;
            string inputText = param.InputText;
            this.GetStringVar(ref inputText, globleData);
            string delay = param.AfterInputDelay;
            this.GetStringVar(ref delay, globleData);
            int delayTime = 0;
            if(!string.IsNullOrEmpty(delay) && (!int.TryParse(delay, out delayTime) || delayTime < 0)) { 
                throw new RpaRuntimeException("输入后延迟时间必须是大于等于零的数字或者为空");
            }
            string inputInterval = param.InputInterval;
            this.GetStringVar(ref inputInterval, globleData);
            int intervalTime = 0;
            int.TryParse(delay, out intervalTime);
            
            BrowserUtil browserUtil;
            switch(webPage.Bt){ 
                case BrowserType.GOOGLE:
                    browserUtil = new ChromeUtil();
                    browserUtil.ActiveBrowser();
                    //如果不追加则清空对话框
                    if(!append) { 
                        NamePipeRequest request1 = new NamePipeRequest();
                        request1.method = DefaultContents.INPUT_TEXT;
                        request1.requestData = new Dictionary<string, object>() { { "tabId", webPage.TabId}, 
                            { "ele", ele }, { "inputText", "" }, { "append", append } };
                        BridgeResponse resp1 = NamedPipeClientUtil.SendRequestV1(request1);
                        if(!resp1.code.Equals(CommunicationCode.OK)) {
                            throw new RpaRuntimeException($"向元素输入出错:{resp1.msg}");
                        }
                    }
                    //获取焦点
                    NamePipeRequest request2 = new NamePipeRequest();
                    request2.method = DefaultContents.GET_FOCUS;
                    request2.requestData = new Dictionary<string, object>() { { "tabId", webPage.TabId}, { "ele", ele }};
                    BridgeResponse resp2 = NamedPipeClientUtil.SendRequestV1(request2);
                    if(!resp2.code.Equals(CommunicationCode.OK)) {
                        throw new RpaRuntimeException($"向元素输入出错:{resp2.msg}");
                    }
                    if(inputType == 0) {
                        //操作键盘输入信息
                        KeyBoardInputNAction ka = new KeyBoardInputNAction();
                        KeyBoardInputNParam kp = new KeyBoardInputNParam();
                        kp.ForceEnglishKeyBoard = true;
                        kp.KeyStep = intervalTime;
                        kp.InputText = inputText;
                        FlowItem tempItem = new FlowItem();
                        tempItem.ControlParam = kp;
                        ka.Execute(currentIndex, tempItem, globleData, flowItems);
                    } else if(inputType == 1) {
                        //设置剪贴板数据
                        SystemUtil.SetClipboardData(inputText);
                        //粘贴
                        SystemUtil.Paste();
                    } else { 
                        //自动化接口输入
                        NamePipeRequest request = new NamePipeRequest();
                        request.method = DefaultContents.INPUT_TEXT;
                        request.requestData = new Dictionary<string, object>() { { "tabId", webPage.TabId}, 
                            { "ele", ele }, { "inputText", inputText }, { "append", append } };
                        BridgeResponse resp = NamedPipeClientUtil.SendRequestV1(request);
                        if(!resp.code.Equals(CommunicationCode.OK)) {
                            throw new RpaRuntimeException($"向元素输入出错:{resp.msg}");
                        }
                    }
                    break;
                case BrowserType.IE:
                    //TODO
                    break;
                case BrowserType.EDGE:
                    //TODO
                    break;
                default:
                    throw new RpaRuntimeException("浏览器类型错误");
            }
            Thread.Sleep(delayTime * 1000);
            return currentIndex;
        }
    }
}
